#lang racket


(require (prefix-in ros: rosetta)
         svn)


; nsis

(define (nsis-process command fn)
  (let ((proc (process command)))
    (let ((proc-in (process-in proc))
          (proc-out (process-out proc))
          (proc-error (process-error proc))
          (proc-fn (process-fn proc)))
      (fn proc-in proc-out proc-error proc-fn)
      (close-output-port proc-in)
      (close-input-port proc-out)
      (close-input-port proc-error))))

(define (nsis-make in out error fn)
  (display-port out)
  (display-port error))

(define (make-nsis-file out-file file-paths)
  (with-output-to-file out-file #:mode 'text #:exists 'truncate/replace
    (λ ()
      (displayln (format "Name \"~A\"" nsis-name))
      (newline)
      (displayln (format "OutFile \"~A\"" nsis-outfile))
      (newline)
      (displayln (format "InstallDir ~A" (nsis-install-dir)))
      (newline)
      (displayln (format "RequestExecutionLevel ~A" nsis-execution-level))
      (newline)
      (displayln "Page directory")
      (displayln "Page instfiles")
      (newline)
      (displayln "Section \"\"")
      (newline)
      (displayln "  SetOutPath $INSTDIR")
      (newline)
      (displayln "  File /r export\\*.*")
      (newline)
      (displayln "SectionEnd ;"))))


; rosetta

(define system-desktop-dir (find-system-path 'desk-dir))
(define system-temporary-dir (find-system-path 'temp-dir))


(define installer-racket-version ros:racket-version)
(define installer-rosetta-version ros:rosetta-version-string)
(define installer-temporary-dir (build-path system-temporary-dir "rosetta-installer"))


(define svn-export-dir (build-path installer-temporary-dir "export"))
(define svn-export-tag-url (format "~Arosetta-~A" (ros:rosetta-lang-tags-url) (installer-rosetta-version)))
(define svn-export-trunk-url (ros:rosetta-lang-trunk-url))


(define nsis-name "Rosetta")
(define nsis-execution-level "admin")
(define nsis-outfile (build-path system-desktop-dir (format "rosetta-~A.exe" (installer-rosetta-version))))
(define (nsis-install-dir) (build-path (format "$APPDATA\\Racket\\~A\\collects\\" (installer-racket-version))))
(define nsis-file-name (build-path installer-temporary-dir "rosetta-installer.nsi"))
(define nsis-make-command (format "makensis ~A" nsis-file-name))


(define (rosetta-svn-export export-url)
  (when (directory-exists? svn-export-dir)
    (delete-directory/files svn-export-dir))
  (svn-export export-url svn-export-dir))

(define (rosetta-make-nsis-file)
  (when (file-exists? nsis-file-name)
    (delete-file nsis-file-name))
  (make-nsis-file nsis-file-name (find-files file-exists? svn-export-dir)))

(define (rosetta-make-nsis-installer)
  (nsis-process nsis-make-command nsis-make))


(define (rosetta-make-tag-installer)
  (rosetta-svn-export svn-export-tag-url)
  (rosetta-make-nsis-file)
  (rosetta-make-nsis-installer))

(define (rosetta-make-trunk-installer)
  (rosetta-svn-export svn-export-trunk-url)
  (rosetta-make-nsis-file)
  (rosetta-make-nsis-installer))